﻿using Alos.Entity;
using Alos.IRepository;
using PetaPoco;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data;
using System.Data.SqlClient;
using Alos.Common;
namespace Alos.Repository
{
    public class ReTaskRepository : BaseRepository<ReTask>, IReTaskRepository
    {
        /// <summary>
        /// 根据用户编号获取教材
        /// </summary>
        /// <param name="id"></param>
        /// <param name="roleid"></param>
        /// <returns></returns>
        public dynamic GetReTaskByResouceId(int id)
        {

            var task = DBContext.SingleOrDefault<dynamic>("select * from ReTask where ResourceID = @0", id);
            var res = DBContext.Query<dynamic>("select * from ReResourceCombinationDetail where TaskID in(select ID from ReTask where ResourceID = @0)", id);
            task.res = res;
            return task;
        }


        /// <summary>
        /// 根据资源Id查询自学任务单
        /// </summary>
        /// <param name="ResourceId">资源Id</param>
        /// <returns>数据集</returns>
        public DataSet GetReTaskByResourceId(int ResourceId)
        {
            string SqlString = @"SELECT A.TaskName,A.TaskGuide,A.TaskRequire,A.ID FROM ReTask A WHERE A.ResourceId=@ResourceId

                                SELECT * FROM ReResource C WHERE C.ID IN(
                                SELECT B.ResourceID FROM ReResourceCombinationDetail
                                B WHERE B.TaskID IN(SELECT A.ID FROM ReTask A WHERE A.ResourceId=@ResourceId)) AND C.ReTypeCode='RE0013'

SELECT * FROM ReResource b WHERE b.ID in(	SELECT a.ResourceID FROM ReResourceCombinationDetail a WHERE a.TaskID in(SELECT a.ID FROM ReTask a WHERE a.ResourceId=@ResourceId))  and b.ResourceFormat='zuhe'

                                SELECT E.ID,F.QuestionRemark FROM ReResource E LEFT JOIN ReTest F ON E.ID=F.ResourceID WHERE E.ID IN( SELECT  A.ResourceID FROM ReComDetail a where a.ComID IN(SELECT D.Id FROM ReComTestType D WHERE ResourceID IN(SELECT C.ID FROM ReResource C WHERE C.ID IN(
                                SELECT B.ResourceID FROM ReResourceCombinationDetail
                                B WHERE B.TaskID IN(SELECT A.ID FROM ReTask A WHERE A.ResourceId=@ResourceId)) AND C.ResourceFormat='zuhe')))";

            SqlParameter[] Parameters = new SqlParameter[] { new SqlParameter("@ResourceId", ResourceId) };
            DataSet DataSetResult = SqlHelper.ExecuteDataset(SqlHelper.GetConnSting(), CommandType.Text, SqlString, Parameters); ;
            SelectById(DataSetResult.Tables[2]);
            SelectById(DataSetResult.Tables[1]);
            return DataSetResult;
        }

        public DataTable SelectById(DataTable dt)
        {
            if (dt != null && dt.Rows.Count > 0)
            {
                string _mids = string.Empty;
                if (dt != null && dt.Rows != null && dt.Rows.Count > 0)
                {
                    foreach (DataRow dr in dt.Rows)
                    {
                        _mids += dr["ID"] + ",";
                    }
                }

                if (!string.IsNullOrWhiteSpace(_mids))
                {
                    Func<string, List<KeyValuePair<int, string>>> gm = (mids) =>
                    {
                        return GetMaterial(mids);
                    };
                    Func<string, List<KeyValuePair<int, string>>> gp = (mids) =>
                    {
                        return GetPoint(mids);
                    };
                    IAsyncResult gmResult = gm.BeginInvoke(_mids.Trim(','), null, null);
                    IAsyncResult gpResult = gp.BeginInvoke(_mids.Trim(','), null, null);
                    List<KeyValuePair<int, string>> gmRtn, gpRtn;
                    gmRtn = gm.EndInvoke(gmResult);
                    gpRtn = gp.EndInvoke(gpResult);
                    dt.Columns.Add("MaterialName", Type.GetType("System.String"));
                    dt.Columns.Add("PointName", Type.GetType("System.String"));

                    foreach (DataRow dr in dt.Rows)
                    {
                        if (gmRtn.Exists(x => x.Key == Convert.ToInt32(dr["ID"])))
                            dr["MaterialName"] = gmRtn.Find(x => x.Key == Convert.ToInt32(dr["ID"])).Value;
                        if (gpRtn.Exists(x => x.Key == Convert.ToInt32(dr["ID"])))
                            dr["PointName"] = gpRtn.Find(x => x.Key == Convert.ToInt32(dr["ID"])).Value;
                    }
                }
            }
            return dt;
        }

        /// <summary>
        /// 加载教材
        /// </summary>
        /// <param name="resourceid"></param>
        /// <returns></returns>
        public List<KeyValuePair<int, string>> GetMaterial(string resourceids)
        {
            string SqlString = @"select distinct A.ResourceID,C.[Version],E.GradeName,D.SubjectName,CASE C.UpOrDown WHEN 1 THEN '上册' ELSE '下册' END UpOrDown,F.PointName from [ReResourseMaterial] A 
                                Left Join [dbo].TeachingMaterialBind B ON A.MaterialID = B.MaterialID
                                Left JOIN [dbo].[TeachingMaterial] C ON B.MaterialID=C.ID
                                Left JOIN [dbo].[DicSubject] D ON C.SubjectCode=D.SubjectCode
                                Left JOIN [dbo].[DicGrade] E ON C.GradeCode=E.GradeCode
                                LeFt JOIN [dbo].[Chapter] F ON F.ID=A.ChapterID where A.ResourceID in(" + resourceids + ")";
            var dt = SqlHelper.ExecuteDataset(SqlString, null).Tables[0];
            List<KeyValuePair<int, string>> _lmaterial = new List<KeyValuePair<int, string>>(), lmaterial = new List<KeyValuePair<int, string>>();
            if (dt != null && dt.Rows.Count > 0)
            {
                foreach (DataRow dr in dt.Rows)
                {
                    _lmaterial.Add(new KeyValuePair<int, string>(Convert.ToInt32(dr["ResourceID"]), dr["Version"].ToString() + dr["GradeName"].ToString() + dr["SubjectName"].ToString() + dr["UpOrDown"].ToString() + "{>>split<<}" + dr["PointName"].ToString()));
                }
                var glm = _lmaterial.GroupBy(x => x.Key);
                string _tmpmalsuff = string.Empty, _tmpmalpre = string.Empty;
                string[] _tmpArr;
                foreach (var lm in glm)
                {
                    lm.ToList().ForEach(item =>
                    {
                        _tmpArr = System.Text.RegularExpressions.Regex.Split(item.Value, "{>>split<<}");
                        _tmpmalsuff += _tmpArr[1] + "、";
                        _tmpmalpre = _tmpArr[0];
                    });
                    if (!string.IsNullOrEmpty(_tmpmalsuff))
                        lmaterial.Add(new KeyValuePair<int, string>(lm.FirstOrDefault().Key, _tmpmalpre + "&gt;" + _tmpmalsuff.Trim('、')));
                    _tmpmalpre = string.Empty;
                    _tmpmalsuff = string.Empty;
                }
            }
            _lmaterial.Clear();
            return lmaterial;
        }
        public List<KeyValuePair<int, string>> GetPoint(string resourceids)
        {
            List<KeyValuePair<int, string>> _lpoint = new List<KeyValuePair<int, string>>(), lpoint = new List<KeyValuePair<int, string>>();
            string SqlString = @"select A.ResourceID,B.PointName from ReResourcePoint A Left Join BasicKnowledgepoint B on A.PointID=B.ID where A.ResourceID in(" + resourceids + ")";
            var dt = SqlHelper.ExecuteDataset(SqlString, null).Tables[0];
            if (dt != null && dt.Rows.Count > 0)
            {
                foreach (DataRow dr in dt.Rows)
                {
                    _lpoint.Add(new KeyValuePair<int, string>(Convert.ToInt32(dr["ResourceID"]), dr["PointName"].ToString()));
                }
                var glm = _lpoint.GroupBy(x => x.Key);
                string _tmppointsuff = string.Empty;
                foreach (var lm in glm)
                {
                    lm.ToList().ForEach(item =>
                    {
                        _tmppointsuff += item.Value + "、";
                    });
                    if (!string.IsNullOrEmpty(_tmppointsuff))
                        lpoint.Add(new KeyValuePair<int, string>(lm.FirstOrDefault().Key, _tmppointsuff.Trim('、')));
                    _tmppointsuff = string.Empty;
                }
            }
            _lpoint.Clear();
            return lpoint;
        }

        public DataTable GetVideoByResourceID(int ResourceId)
        {
            throw new NotImplementedException();
        }

        public DataSet GetTaskZuHe(int ResourceId)
        {
            throw new NotImplementedException();
        }
    }
}
